#!/usr/bin/env python
#coding:utf-8
from min_p import *
reload(sys)
sys.setdefaultencoding("utf-8")
from selenium import webdriver  
from selenium.webdriver.common.keys import Keys
import tkinter as tk
from tkinter.ttk import *
import threading
import tkFileDialog
class MyThread(threading.Thread):
    def __init__(self, func, *args):
        super(MyThread,self).__init__()  
        self.func = func
        self.args = args
        self.setDaemon(True)
        self.start()    # 在这里开始  
    def run(self):
        self.func(*self.args)

class TAOBAO_UP_DOWN():
    def __init__(self):
        chromedriver = "chromedriver.exe"
        self.driver = webdriver.Chrome(executable_path=chromedriver)
        self.driver.set_window_size(1280,800)
        self.driver.get('https://myseller.taobao.com/home.htm')

    #出售中的商品
    def get_down_page(self):
        try:
            sell_url = self.driver.find_element_by_link_text(u'出售中的宝贝').get_attribute('href')
            self.driver.get(sell_url)
            time.sleep(1)
            return True
        except Exception, e:
            return log_wrong()

    #仓库中的商品
    def get_up_page(self):
        try:
            store_url = self.driver.find_element_by_link_text(u'仓库中的宝贝').get_attribute('href')
            self.driver.get(store_url)
            time.sleep(1)
            return True
        except Exception, e:
            return log_wrong()

        
    #检查登录状态（登录时用）
    def check_login(self):
        if "https://myseller.taobao.com/home.htm" in self.driver.current_url[0:60]:
            return True
        else:
            return False    

    #检查元素是否存在
    def isElementExist(self,element):
        try:
            self.driver.find_element_by_xpath(element)
            return True
        except Exception, e:
            return False
    #关闭浏览器
    def close(self):
        self.driver.quit()

    #下架操作
    def down(self,code):
        try:
            self.driver.find_element_by_xpath('//*[@id="outer-id"]').clear()
            self.driver.find_element_by_xpath('//*[@id="outer-id"]').send_keys(code)#查找
            self.driver.find_element_by_xpath('//*[@id="outer-id"]').send_keys(Keys.ENTER)
        except Exception, e:
            return log_wrong()
        time.sleep(1)
        if self.isElementExist('//*[@id="J_DataTable"]/div[2]/table/thead/tr[2]/td/div/input[2]'):
            try:
                self.driver.find_element_by_xpath('//*[@id="J_DataTable"]/div[2]/table/thead/tr[2]/td/div/input[2]').click()
                self.driver.find_element_by_xpath('//*[@id="J_DataTable"]/div[2]/table/thead/tr[2]/td/div/button[1]').click()
                return True
            except Exception, e:
                return log_wrong()
        else:
            return None

    #检查下架状态  返回[1,0]成功和失败数
    def check_down_state(self):
        try:
            time.sleep(1)
            if self.isElementExist('//*[@id="main-content"]/div[2]/div[2]'):
                result = self.driver.find_element_by_xpath('//*[@id="main-content"]/div[2]/div[2]').text
                if u"成功" in result:
                    success,fail = re_all('[0-9]',result)
                    return [success,fail]
                else:
                    return False
            else:
                return False
        except Exception, e:
            return log_wrong()

    #上架操作
    def up(self,code):
        try:
            self.driver.find_element_by_xpath('//*[@id="outer-id"]').clear()
            self.driver.find_element_by_xpath('//*[@id="outer-id"]').send_keys(code)
            self.driver.find_element_by_xpath('//*[@id="outer-id"]').send_keys(Keys.ENTER)
        except Exception, e:
            return log_wrong()
        time.sleep(1)
        if self.isElementExist('//*[@id="upShelfSingle"]'):
            try:
                self.driver.find_element_by_xpath('//*[@id="all-select1"]').click()
                self.driver.find_element_by_xpath('//*[@id="J_DataTable"]/div[3]/table/tbody/tr/td/div/button').click()
                return True
            except Exception, e:
                return log_wrong()        
        else:
            return None

    #检查上架状态  返回[1,0]成功和失败数
    def check_up_state(self):
        try:
            time.sleep(1)
            if self.isElementExist('//*[@id="main-content"]/div[1]'):
                result = self.driver.find_element_by_xpath('//*[@id="main-content"]/div[1]').text
                if u"成功" in result:
                    success,fail = re_all('[0-9]',result)
                    return [success,fail]
                else:
                    return False
            else:
                return False
        except Exception, e:
            return log_wrong()

class MyApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title(u'自动化')
        self.mystate = "等待任务中"
        self.run_state = False
        self.setupUI()
        self.fname = None
        
    def setupUI(self):
        row0 = tk.Frame(self)
        row0.pack(fill="x")
        tk.Label(row0, text='淘宝批量上下架-C店版', width=35).pack(side=tk.LEFT)
        row1 = tk.Frame(self)
        row1.pack(fill="x")
        tk.Button(row1, text="导入文件", command=self.do_open).pack(side=tk.LEFT,ipadx=10,padx=5,pady=5)
        tk.Button(row1, text="批量下架", command=lambda :MyThread(self.do_down,)).pack(side=tk.LEFT,ipadx=45,padx=5,pady=5)

        row2 = tk.Frame(self)
        row2.pack(fill="x")
        tk.Button(row2, text="导入文件", command=self.do_open).pack(side=tk.LEFT,ipadx=10,padx=5,pady=5)
        tk.Button(row2, text="批量上架", command=lambda :MyThread(self.do_up,)).pack(side=tk.LEFT,ipadx=45,padx=5,pady=5)
        row3 = tk.Frame(self)
        row3.pack(fill="x")
        self.label = tk.Label(row3, text=self.mystate, width=35,anchor = 'w')
        self.label.pack(side=tk.LEFT)
    #获取操作列表
    def get_list(self):
        try:
            self.mission_list = open(self.fname).read().strip().split("\n")
        except Exception, e:
            return []
    #打开文件
    def do_open(self):
        self.fname = tkFileDialog.askopenfilename(title=u"选择文件")
        self.file_name = self.fname.split('/')[-1]
        self.log_name = self.file_name+".log.csv"
        self.label.config(text="已选择文件: "+self.file_name)

    def do_down(self):
        #检查是否有任务进行中
        if self.run_state==True:
            self.mystate = "操作进行中,请稍等..."
            self.label.config(text=self.mystate)   
            return False
        #设置当前为运行状态   
        self.run_state = True
        #检查批量文件是否有选择
        if self.fname==None:
            self.label.config(text="请先选择文档！")
            self.run_state = False  
            return False
        #获取操作文档的列表大小            
        self.get_list()
        self.mission_num = len(self.mission_list)
        if self.mission_num<=0:
            self.label.config(text="文件错误,无法获取操作列表！")
            self.run_state = False  
            return False
        #################################################################
        new = TAOBAO_UP_DOWN()
        self.label.config(text="请登陆淘宝")
        while True:
            if new.check_login():
                self.label.config(text="登陆成功")
                break
            else:
                time.sleep(5)
        if new.get_down_page()==False:
            self.label.config(text="浏览器操作失败,请重试！")
            self.run_state = False
            new.close()   
        z = 1
        for code in self.mission_list:
            state = new.down(code)
            if state==True:
                result = new.check_down_state()
                if type(result)==list:
                    _text = "%s/%s 商家编码:%s 成功:%s,失败:%s"%(z,self.mission_num,code,result[0],result[1])
                    _log_text = "down,%s,%s,%s,d"%(code,result[0],result[1])
                else:
                    _text = "%s/%s 商家编码:%s 操作失败！"%(z,self.mission_num,code)
                    _log_text = "down,%s,%s,%s"%(code,0,1)
            else:
                _text = "%s/%s 商家编码:%s 操作失败！"%(z,self.mission_num,code)
                _log_text = "down,%s,%s,%s"%(code,0,1)
            self.label.config(text=_text)
            log(_log_text,self.log_name,False)
            time.sleep(0.5)                
            z = z+1
        new.close()

        #################################################################
        self.mystate = "批量操作已完成！"
        self.label.config(text=self.mystate)
        self.run_state = False
        self.fname = None

    def do_up(self):
        #检查是否有任务进行中
        if self.run_state==True:
            self.mystate = "操作进行中,请稍等..."
            self.label.config(text=self.mystate)   
            return False
        #设置当前为运行状态   
        self.run_state = True
        #检查批量文件是否有选择
        if self.fname==None:
            self.label.config(text="请先选择文档！")
            self.run_state = False  
            return False
        #获取操作文档的列表大小            
        self.get_list()
        self.mission_num = len(self.mission_list)
        if self.mission_num<=0:
            self.label.config(text="文件错误,无法获取操作列表！")
            self.run_state = False  
            return False
        #################################################################
        new = TAOBAO_UP_DOWN()
        self.label.config(text="请登陆淘宝")
        while True:
            if new.check_login():
                self.label.config(text="登陆成功")
                break
            else:
                time.sleep(5)
        if new.get_up_page()==False:
            self.label.config(text="浏览器操作失败,请重试！")
            self.run_state = False
            new.close()  
        z = 1
        for code in self.mission_list:
            state = new.up(code)
            if state==True:
                result = new.check_up_state()
                if type(result)==list:
                    _text = "%s/%s 商家编码:%s 成功:%s,失败:%s"%(z,self.mission_num,code,result[0],result[1])
                    _log_text = "up,%s,%s,%s,d"%(code,result[0],result[1])
                else:
                    _text = "上架,%s/%s 商家编码:%s 操作失败！"%(z,self.mission_num,code)
                    _log_text = "up,%s,%s,%s"%(code,0,1)
            else:
                _text = "%s/%s 商家编码:%s 操作失败！"%(z,self.mission_num,code)
                _log_text = "up,%s,%s,%s"%(code,0,1)
            self.label.config(text=_text)
            log(_log_text,self.log_name,False)
            time.sleep(0.5)               
            z = z+1
        new.close()

        #################################################################
        self.mystate = "批量操作已完成！"
        self.label.config(text=self.mystate)
        self.run_state = False 
        self.fname = None          

if __name__ == '__main__':
    new = MyApp()
    new.mainloop()